<template>
  <div ref="containerRef" class="list-container" @scroll="scrollHandler">
    <div class="pillar" :style="{ height: `${listData.length * itemHeight}px` }"></div>

    <ul
      ref="listRef"
      class="list"
      :style="{ transform: `translateY(${topIndex * itemHeight}px)` }"
    >
      <li
        class="item"
        v-for="(num, index) in visiableData"
        :key="index"
        :style="{ height: itemHeight + 'px', lineHeight: itemHeight + 'px' }"
      >
        {{ num }}
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
const { listData } = defineProps<{
  listData: number[];
}>();

const listRef = ref<HTMLLIElement>();
const containerRef = ref<HTMLDivElement>();
const count = ref<number>(0);
const topIndex = ref<number>(0);

const itemHeight = 40;

function scrollHandler() {
  const offset = containerRef.value?.scrollTop || 0;
  topIndex.value = Math.floor(offset / itemHeight);
}

const visiableData = computed(() => {
  return listData.slice(topIndex.value, topIndex.value + count.value);
});

onMounted(() => {
  console.log(listRef.value?.offsetHeight);
  const containerHeight = listRef.value?.offsetHeight || 0;
  count.value = Math.ceil(containerHeight / itemHeight) + 1;
});
</script>

<style lang="less" scoped>
.list-container {
  position: relative;
  overflow-y: scroll;
  height: 100%;
}

.list {
  position: absolute;
  top: 0;
  height: 100%;
}
</style>
